/**
 * ----------------------------------------------------------------------------
 * Copyright Jens Konopka
 * 
 * Alle Rechte vorbehalten.
 * Licence: Apache 2.0
 * ----------------------------------------------------------------------------
 *
 * created on 05.03.2012 by jkonopka
 */
package de.sql.toolkit.exporter;

import java.io.File;
import java.util.List;

import de.sql.toolkit.generator.TableCreateScriptColumnGenerator;
import de.sql.toolkit.generator.TableCreateScriptGenerator;
import de.sql.toolkit.model.Table;
import de.sql.toolkit.reader.CreateTableScriptReader;
import de.sql.toolkit.util.FilenameUtil;

/**
 * @author jkonopka
 * 
 */
public class TableCreateScriptExporter extends AbstractExporter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8520540073989238412L;

	/**
	 * @param dstPath
	 * @param schema
	 */
	public TableCreateScriptExporter(File dstPath, String schema) {
		super(dstPath, schema);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.sql.toolkit.exporter.IExporter#export()
	 */
	@Override
	public void export() throws Exception {
		validateDstPath();
		final CreateTableScriptReader reader = new CreateTableScriptReader(getSchema());
		final List<Table> list = reader.read();
		for (final Table table : list) {
			final Thread thread = new Thread() {

				/*
				 * (non-Javadoc)
				 * 
				 * @see java.lang.Thread#run()
				 */
				@Override
				public void run() {
					try {
						final TableCreateScriptGenerator writer = new TableCreateScriptGenerator(table, getDstPath());
						writer.add(new TableCreateScriptColumnGenerator(table, getDstPath()));
						final String content = writer.generate();
						final String filename = createFilename("CREATE_TABLE_" + table.getName().toUpperCase());
						writeContentToFile(filename, content);
					} catch (final Exception e) {
						e.printStackTrace();
					}
				}
			};
			thread.start();
		}
	}
	
	/**
	 * @param filename
	 * @return
	 */
	protected String createFilename(final String filename) {
		final StringBuilder sb = new StringBuilder();
		final String path = getDstPath().getAbsolutePath();
		final String concat = FilenameUtil.concat(path, filename);
		sb.append(concat);
		sb.append(".sql");
		return sb.toString();
	}

}
